import config from "../config.js";
import $kt from "../node-server-kantboot-util/index.js";
import RestResult from '../rest/RestResult.js'
import WebSocket from 'ws';
import axios from "axios";

const port = config.websocket.port;
const wss = new WebSocket.Server({port});

let map = new Map();

emitter.on("websocketSend", (json) => {
    send(map.get(json.memory), json);
});

let send = (ws, message) => {
    if (!ws) {
        return;
    }
    if (ws.readyState === 1) {
        try {
            ws.send(JSON.stringify(message));
        } catch (e) {
        }
    }
}


wss.on('connection', async function connection(ws, req) {
    // 获取ws客户端的ip地址、端口号、和user-agent
    console.log('ws客户端连接：', ws._socket.remoteAddress, ws._socket.remotePort);
    // 获取用户的kantbootMemory（即请求地址中最后一截）
    let kantbootMemory = $kt.uri.getLastPath(req?.url);
    console.log('用户的kantbootMemory:', kantbootMemory);

    // 向中台发检测kantbootMemory是否有效
    await axios.post(`${config.middleground.url}/middleground-common-web/tokenMemory/checkMemory`,
        {memory: kantbootMemory}).then((res) => {
        if (res.data.success) {
            if (res.data.data) {
                // Websocket连接可用
                send(ws, RestResult.success(null, "websocketConnectSuccess", "Websocket连接可用"));
                try {
                    axios.post(`${config.middleground.url}/socket-websocket-web/socketWebsocket/generate`, {memory: kantbootMemory});
                } catch (e) {

                }
                map.set(kantbootMemory, ws);
                console.log("Websocket连接可用", ws._socket.remoteAddress, ws._socket.remotePort, kantbootMemory);
            } else {
                // Websocket连接不可用
                send(ws, RestResult.error("websocketConnectError", "Websocket连接不可用"));
                console.log("Websocket连接不可用", ws._socket.remoteAddress, ws._socket.remotePort, kantbootMemory);
                try {
                    ws.close();
                } catch (e) {
                    console.log("异常断开")
                }
            }
        }
    }).catch(e => {
        // Websocket连接不可用
        send(ws, RestResult.error("websocketConnectError", "Websocket连接不可用"));
        console.log("Websocket连接不可用", ws._socket.remoteAddress, ws._socket.remotePort, kantbootMemory);
        try {
            ws.close();
        } catch (e) {
            console.log("异常断开")
        }
    })
    ws.on('message', async function incoming(jsonStr) {
        // 发送心跳
        let json = JSON.parse(jsonStr);
        if (json.operateCode === "heartbeat") {
                // 告诉中台心跳了
                await axios.post(`${config.middleground.url}/socket-websocket-web/socketWebsocket/heartbeat`, {memory: kantbootMemory}).catch((e)=>{

                });
        }
    });

    // 监听断开
    ws.on('close', function close() {
        console.log('ws客户端断开连接');
    });

});

// 监听服务是否启动成功
wss.on('listening', function () {
    console.log(`WebSocket服务端口：${port}`);
});


export default wss;